import unittest
from playful.timer import mapper
import time


class test_timer(unittest.TestCase):
	def test_timer_may_be_restarted(self):
		timer = self._arrange_timer()
		mappings = self._arrange_mappings()
		mapped_values = {}

		timer.map([], mappings, mapped_values)

		timer.map(['tr'], mappings, mapped_values)

		self.assertEqual(mapped_values['timer'], 'restart 1')

	def test_strict_mapping_still_maps(self):
		timer = self._arrange_timer()
		mappings = self._arrange_mappings()
		mapped_values = {}

		timer.map([], mappings, mapped_values)

		timer.map(['on'], mappings, mapped_values)

		self.assertEqual(mapped_values['map'], 'map on')

	def slow_test_add_without_restart_will_count_down_without_trigger(self):
		timer = self._arrange_timer()
		mappings = self._arrange_mappings()
		mapped_values = {}

		timer.map([], mappings, mapped_values)

		timer.map(['add'], mappings, mapped_values)
		self.assertEqual(timer._timers[0]['seconds'], 1 + 2)
		time.sleep(3)
		timer.map([], mappings, mapped_values)

		self.assertEqual(timer._timers[0]['seconds'], 1)

	def _arrange_mappings(self):
		return [
			{
				'input': 'on',
				'output':
					{
						'name': 'map',
						'state': 'map on'
					}
			},
			{
				'input': 'off',
				'output':
					{
						'name': 'map',
						'state': 'off'
					}
			}
		]

	def _arrange_timer(self):
		config = {
			'_timers': [
				{
					'name': 't1',
					'on_end': [
						{
							'name': 'timer',
							'weight': 1,
							'state': 't1 end'
						},
					],
					'min': 1,
					'max': 300
				}
			],
			'_conditions': [
				{
					'logic': 'and',
					'internal': '$random',
					'operator': '>',
					'constant': 0.5,
					'result': [
						{
							'name': 'condition',
							'weight': 1,
							'state': 'condition'
						}
					]
				}
			],
			'tr': [
				{
					'timer': {'name': 't1', 'action': 'restart'}},
				{'state': [
					{
						'name': 'timer',
						'weight': 1,
						'state': 'restart $t1_counter'},
				]}
			],
			'add': [
				{'seconds': {'name': 't1', 'action': 'add', 'value': 2}},
				{'state': [
					{
						'name': 'timer',
						'weight': 1,
						'state': 'add 2 is now $t1_seconds'},
				]}
			],
			'sub': [
				{'seconds': {'name': 't1', 'action': 'subtract', 'value': 3}},
				{'state': [
					{
						'name': 'timer',
						'weight': 1,
						'state': 'sub 3 is now $t1_seconds'}
				]}
			]
		}

		timer = mapper(config)

		return timer
